from django.shortcuts import render
from django.template.defaultfilters import random
from rest_framework.response import Response
from rest_framework.views import APIView
import re

from user.models import UserModels
from user.userser import UserSer
from utils import myjwt
from utils.authentication import MyAuthentication
from utils.duanxin import send_message
from utils.myRedis import rediss


# Create your views here.
#用户注册验证
class UserAPIView(APIView):
    def post(self, request):
        use = {}
        account = request.data.get("account")
        password = request.data.get("password")
        # 手机号验证
        if re.match(r'^1[3456789]\d{9}$', account):
            use["phone"] = account
            phonee = UserModels.objects.filter(phone=account).first()
            if phonee != None:
                return Response({"msg": "注册失败，该用于已经存在"})
        elif re.match(r"^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$", account):
            use["email"] = account

        else:
            use["username"] = account

        use['password'] = password

        new = UserSer(data=use)

        if new.is_valid():
            new.save()
            return Response({"msg": "注册成功"})
        else:
            return Response({"msg": new.errors})


# 登录
class Userdeng(APIView):
    def post(self, request):
        account = request.data.get("account")
        password = request.data.get("password")
        if re.match(r'^1[3456789]\d{9}$', account):
            acc = UserModels.objects.filter(phone=account)
        elif re.match(r"^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$", account):
            acc = UserModels.objects.filter(email=account)
        else:
            acc = UserModels.objects.filter(username=account)
        if acc:
            if acc[0].password == password:
                jwt = myjwt.jwtweb.gettoken(acc[0].id, acc[0].password)
                return Response({"msg": "登录成功", "token": "Bearer " + jwt, "id": acc[0].id, "code": 201}, )
            else:
                return Response({"msg": "密码错误", 'code': 402})
        else:
            return Response({"msg": "账号不存在", 'code': 402})

# 手机号登录验证
class LoginCode(APIView):
    def post(self, request):
        code = request.data.get("code")
        phone = request.data.get("account")
        print(code)
        if re.match(r'^1[3456789]\d{9}$', phone):
            code1 = rediss.getstr(phone)
            if code1 == code:
                phonee = UserModels.objects.filter(phone=phone)
                if phonee != None:
                    tokenjwt = myjwt.jwtweb.gettoken(phone, phonee[0].id)
                    return Response({"code":201,"msg":"登录成功","token":tokenjwt,"id":phonee[0].id})
                else:
                    user = {}
                    user['phone'] = phone
                    user['password'] = "000000"
                    new = UserSer(data=user)
                    if new.is_valid():
                         new.save()
                         token=myjwt.jwtweb.gettoken(phone,phonee[0].id)
                         return Response({"code":201,"msg":"登录成功","token":token,"id":phonee[0].id})
            else:
                return Response("验证码错误")
        else:
            return Response("手机号错误")
#     发送验证码
import random
class fasongCode(APIView):
    def post(self, request):
        phone = request.data.get("account")
        code = str(random.randint(1000, 9999))
        br = send_message(phone, code)
        rediss.setex(phone, code, 60 * 2)
        if br:
            return Response("验证密码发送成功")
        else:
            return Response("验证吗发送失败")

# token测试
class Test(APIView):
    authentication_classes = [MyAuthentication]
    def get(self,request):
        return  Response("hello")

    # def post(self,request):
    #     UserModels.objects.create(phone=request.data.get("account"),password=request.data.get("password"))
    #     userser = UserSer(data=request.data)
    #     if userser.is_valid():
    #         userser.save()
    #
    # def put(self,request):
    #     User=UserModels.objects.get(id=request.data.gat('id'))
    #     user=UserSer(data=request.data,initial=User)
    #     if user.is_valid():
    #         user.save()
    #
    # def delete(self,request):
    #     user=UserModels.objects.get(id=request.data.gat('id'))
